package com.lei.springbootpractice.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private NotificationTableCreator tableCreator;

    @Override
    public void run(String... args) throws Exception {
        try {
            // 检查notification_status表是否存在
            String checkTableSql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'NOTIFICATION_STATUS'";
            Integer count = jdbcTemplate.queryForObject(checkTableSql, Integer.class);
            
            if (count == null || count == 0) {
                System.out.println("=== 初始化通知状态表 ===");
                tableCreator.createNotificationTable();
                System.out.println("=== 通知状态表初始化完成 ===");
            } else {
                System.out.println("=== 通知状态表已存在，跳过初始化 ===");
                // 验证表结构
                try {
                    jdbcTemplate.queryForObject("SELECT COUNT(*) FROM notification_status", Integer.class);
                    System.out.println("=== 通知状态表验证成功 ===");
                } catch (Exception e) {
                    System.err.println("=== 通知状态表验证失败，重新创建 ===");
                    tableCreator.createNotificationTable();
                    System.out.println("=== 通知状态表重新创建完成 ===");
                }
            }
        } catch (Exception e) {
            System.err.println("数据库初始化失败: " + e.getMessage());
            e.printStackTrace();
            // 尝试强制创建表
            try {
                System.out.println("=== 尝试强制创建通知状态表 ===");
                tableCreator.createNotificationTable();
                System.out.println("=== 强制创建完成 ===");
            } catch (Exception ex) {
                System.err.println("强制创建也失败了: " + ex.getMessage());
            }
        }
    }

    private void executeScript(String scriptPath) throws Exception {
        ClassPathResource resource = new ClassPathResource(scriptPath);
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            
            StringBuilder sqlBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                
                // 跳过注释和空行
                if (line.isEmpty() || line.startsWith("--")) {
                    continue;
                }
                
                sqlBuilder.append(line).append(" ");
                
                // 如果行以分号结尾，执行SQL语句
                if (line.endsWith(";")) {
                    String sql = sqlBuilder.toString().trim();
                    if (!sql.isEmpty()) {
                        try {
                            // 移除末尾的分号
                            sql = sql.substring(0, sql.length() - 1);
                            jdbcTemplate.execute(sql);
                            System.out.println("执行SQL: " + sql.substring(0, Math.min(50, sql.length())) + "...");
                        } catch (Exception e) {
                            System.err.println("执行SQL失败: " + sql);
                            System.err.println("错误: " + e.getMessage());
                        }
                    }
                    sqlBuilder.setLength(0);
                }
            }
        }
    }
} 